<template>
    <view class="w-form-input" v-if="!readonly">
        <uni-easyinput class="uni-mt-5" v-model="_value" :clearable="false" disabled
            :placeholder="$t('module.selectData')" style="color:#000">
            <template #right>
                <button style="display: flex;justify-content: center;align-items: center" class="mini-btn solt-botton" type="default" size="mini"
                    @click="iconClick">{{ $t('module.select') }}</button>
            </template>
        </uni-easyinput>
        <uni-popup ref="popup" type="center" class="popup-content" background-color="#fff" :mask-click="false">
            <view class="input-dialog-box" style="height:700rpx;overflow: hidden;">
                <view class="input-dialog-content">
                    <view class="header">
                        <uni-easyinput v-model="data.keyWord" focus :placeholder="$t('webAuto.EnterKeywords')"
                            @change="inputClick"></uni-easyinput>
                    </view>
                    <view class="element-auto" style="height: 600rpx">
                        <zb-table :show-header="true" :columns="data.tableHeader" :stripe="true" :fit="true"
                            :border="true" :data="data.tableData" @rowClick="rowClick"
                            :cell-header-style="cellHeaderStyle" :highlight="true"></zb-table>
                    </view>
                </view>
            </view>
            <view class="input-dialog-footer">
                <view class="input-dialog-button" @click="cancelFn">
                    {{ $t('webAuto.cancel') }}
                </view>
                <view class="input-dialog-button dialog-button-left" @click="confirmFn">
                    {{ $t('calendar.confirm') }}
                </view>
            </view>
        </uni-popup>
    </view>
    <view class="w-form-input-rv" v-else>
        <text style="line-height:70rpx">{{ _value }}</text>
    </view>

</template>

<script setup>
import { computed, ref, reactive } from 'vue'
import { $nEmpty } from '@/utils/tool.js'
import tableColor from '@/utils/tableColor.js'
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const props = defineProps({
    modelValue: { //表单双向绑定的值
        type: String
    },
    formData: { //表单值
        type: Object
    },
    formProps: { //表单联动相关配置
        type: Object,
        default: () => {
            return {}
        }
    },
    readonly: Boolean
})

const _value = computed({
    get() {
        return props.modelValue
    },
    set(val) {
        emits('update:modelValue', val)
    }
})
const data = reactive({
    data: '',
    tableHeader: [],
    tableData: [],
    pageSize: 15,
    // 当前页
    currentPage: 1,
    // 数据总量
    total: 0,
    preHandlerFuc: null,
    loading: false,
    keyWord: '',
    rowLi: {},
    highlightedRow: null
})
const emits = defineEmits(['update:modelValue'])
const { cellHeaderStyle } = tableColor()
// 弹框
const popup = ref(null)
const iconClick = (type) => {
    data.keyWord = ''
    doRequest()
    popup.value.open()
}
// 弹框确定
const confirmFn = () => {
    if (data.rowLi == null || Object.keys(data.rowLi).length == 0) {
        uni.showToast({ title: t('module.selectData'), icon: 'error' })
        return
    } else {
        // console.log('data.rowLi', data.rowLi)
        // 点击确定后进行赋值
        props.formProps.options.forEach(item => {
            let a = item.name
            Object.values(props.formData).forEach(label => {
                props.formData[a] = data.rowLi[item.value]
                if (typeof label == 'object') {
                    label.forEach(items => {
                        if (Object.keys(items).indexOf(a) != -1) {
                            // let rowArr = store.state.formItem
                            // rowArr.forEach(row => {
                            //     if (Object.keys(row).length > 0 && Object.keys(row).indexOf(item.value) != -1) { //判断选择的数据是否存在并且有没有绑定
                            //         // 判断表格列是否添加过信息
                            //         if (items[a]?.length > 0 && this.index - 1 > 0) {
                            //             label[this.index - 1][a] = this.rowLis[item.value]
                            //         } else {
                            //             items[a] = row[item.value]
                            //         }
                            //     }
                            // })
                            items[a] = data.rowLi[item.value]
                        }
                    })
                } else {
                    props.formData[a] = data.rowLi[item.value]
                }
            })
        })
        popup.value.close();
    }
}

// 表格事件 选择某行数据
const rowClick = (row, column) => {
    data.rowLi = row
    data.highlightedRow = column
}

// 查询
const inputClick = () => {
    doRequest()
}

// 取消关闭弹框
const cancelFn = () => {
    popup.value.close();
}

const doRequest = () => {
    data.tableData = []
    data.tableHeader = []
    const http = props.formProps.http || {}
    if (http.url && http.method) {
        const params = {
            url: http.url,
            method: http.method.toLowerCase(),
            headers: {
                'content-type': http.contentType === 'JSON' ? 'application/json' :
                    'application/x-www-form-urlencoded',
                ...coverParams(http.headers || [])
            },
            // formData: Object.assign({}, props.formData),
            params: {}, //查询条件
            data: props.formProps.http.contentType === 'JSON' ? JSON.parse(bindVar(props.formProps.http.data || '{}')) : coverParams(props.formProps.http.params || [])
        }
        params.params.value = data.keyWord   //表格自定义的查询条件 关键字查询
        params.params.pageSize = data.pageSize //分页 第几页
        params.params.pageNo = data.currentPage  //分页 每页条数
        preHandler(params, props.formProps.http.preHandler)
        //这里由于前置处理后，可能修改params参数，所以需要重新处理
        if (props.formProps.http.contentType !== 'JSON') {
            params.data = { ...params.data, ...params.params }
        }
        data.loading = true
        uni.request({
            ...params,
            timeout: 20000,
            header: params.headers,
            dataType: 'json',
            success: (rsp) => {
                // 接口返回数据赋值给表格，自定义处理了，就没有后置处理
                // console.log(props.formProps.options)
                // 循环比对表格表头
                let arr = Object.keys(rsp.data.model)
                props.formProps.options.forEach(item => {
                    arr.forEach(name => {
                        if (name === item.value && item.placeholder) {
                            data.tableHeader.push({
                                name: item.value, label: item.placeholder
                            })
                        }
                    })
                })
                // console.log(data.tableHeader)
                // console.log(rsp.data.data)
                data.loading = false
                data.tableData = rsp.data.data
                data.total = rsp.data.total
            },
            fail: (err) => {
                data.loading = false
                uni.showToast({
                    icon: 'none',
                    title: '请求http数据源发生异常:' + JSON.stringify(err)
                })
            }

        })
    }
}

//前置处理
const preHandler = (params, script) => {
    if (!data.preHandlerFuc) {
        data.preHandlerFuc = new Function('ctx', `${script}\n preHandler(ctx)`)
    }
    try {
        data.preHandlerFuc(params)
    } catch (e) {
        // console.log(e)
    }
}
const bindVar = (str) => {
    return str.replace(/\$\{(\w+)\}/g, (match, key) => {
        return props.formData[key] || '';
    })
}
//数组转对象
const coverParams = (args, isForm = false) => {
    const params = {};
    if (Array.isArray(args)) {
        args.forEach(arg => {
            if ($nEmpty(arg.name)) {
                params[arg.name] = arg.value.replace(/\$\{(\w+)\}/g, (match, key) => {
                    return props.formData[key] || '';
                })
            }
        })
    } else {
        params = { ...args }
    }
    if (isForm) {
        return Object.keys(params).map(v => `${v}=${params[v]}`).join('&')
    }
    return params
}
</script>

<style scoped>
.is-disabled,
.uni-input-input {
    color: rgb(0, 0, 0) !important;
    /* 将灰色改为你想要的颜色 */

}

.element-auto{
    height: 100%;
    width: 100%;
    overflow: auto;
}
.solt-botton {
    height: 70rpx;
    border-radius: 0;

}

/* 高亮行的CSS样式 */
.highlighted-row {
    background-color: #f0f0f0;
    /* 高亮颜色 */
}

@mixin flex {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: row;
}

@mixin height {
    /* #ifndef APP-NVUE */
    height: 100%;
    /* #endif */
    /* #ifdef APP-NVUE */
    flex: 1;
    /* #endif */
}

.box {
    @include flex;
}

.button {
    @include flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    height: 35px;
    margin: 0 5px;
    border-radius: 5px;
}

.example-body {
    background-color: #fff;
    padding: 10px 0;
}

.button-text {
    color: #fff;
    font-size: 12px;
}

.popup-content {
    @include flex;
    align-items: center;
    justify-content: center;
    padding: 15px;
    height: 50px;
    background-color: #fff;
}

.popup-height {
    @include height;
    width: 200px;
}

.text {
    font-size: 12px;
    color: #333;
}

.popup-success {
    color: #fff;
    background-color: #e1f3d8;
}

.popup-warn {
    color: #fff;
    background-color: #faecd8;
}

.popup-error {
    color: #fff;
    background-color: #fde2e2;
}

.popup-info {
    color: #fff;
    background-color: #f2f6fc;
}

.success-text {
    color: #09bb07;
}

.warn-text {
    color: #e6a23c;
}

.error-text {
    color: #f56c6c;
}

.info-text {
    color: #909399;
}

.dialog,
.share {
    /* #ifndef APP-NVUE */
    display: flex;
    /* #endif */
    flex-direction: column;
}

.dialog-box {
    padding: 20rpx;
}

.dialog .button,
.share .button {
    /* #ifndef APP-NVUE */
    width: 100%;
    /* #endif */
    margin: 0;
    margin-top: 20rpx;
    padding: 6rpx 0;
    flex: 1;
}

.dialog-text {
    font-size: 14px;
    color: #333;
}

/* 输入对话框样式 */
.input-dialog-box {
    width: 700rpx;
    background-color: #FFFFFF;
    border-radius: 22rpx;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.input-dialog-footer {
    height: 80rpx;
    display: flex;
    flex-direction: row;
    border-top-color: #f5f5f5;
    border-top-style: solid;
    border-top-width: 2rpx;
}

.input-dialog-button {
    display: flex;
    flex: 1;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 90rpx;
    color: #333;
}

.input-dialog-content {
    padding: 20rpx;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.input-dialog-button {
    display: flex;
    flex: 1;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 80rpx;
    color: #333;
}

.dialog-button-left {
    border-left-color: #f0f0f0;
    border-left-style: solid;
    border-left-width: 1px;
    color: #007aff;
}

.header {
    height: auto;
    margin-bottom: 20rpx;
}

.header-view {
    font-size: 30rpx;
    line-height: 60rpx;
    font-weight: 600;
}

.input-dialog-footer {
    display: flex;
    flex-direction: row;
    border-top-color: #f5f5f5;
    border-top-style: solid;
    border-top-width: 1px;
}
</style>
